package com.qdxht.dispenser.utils.update;


import com.qdxht.dispenser.ui.models.entity.BaseData;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.lang.reflect.Type;


/**
 * json 转换工具
 * @author yzh
 * @email  yzh@boot.com
 * @date   2018-01-07 18:30:52
 */
public class JsonUtils {

    private final static Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .create();
    /**
     * 对象转字符串
     * @param ob
     * @return
     */
    public static String toJson(Object ob) {
        if(ob == null) {
            return gson.toJson(new Object());
        }
        return gson.toJson(ob);
    }

    /**
     * 字符串转对象
     * @return
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        try{
            return gson.fromJson(json, clazz);
        } catch (Exception e){
            return null;
        }
    }

    /**
     * 字符串Type转对象
     * @return
     */
    public static <T> T fromJson(String json, Type typeOfT) {
        try{
            return gson.fromJson(json, typeOfT);
        } catch (Exception e){
            return null;
        }
    }

    public static BaseData getData(String json) {
        try{
            BaseData baseData = gson.fromJson(json, BaseData.class);
            if(baseData == null){
                baseData = new BaseData("999","数据异常");
            }
            return baseData;
        }catch (Exception e){
            return new BaseData("999","数据异常");
        }
    }

}
